﻿
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
//using TouchSocket.Core.Config;
//using TouchSocket.Core.Plugins;
//using TouchSocket.Sockets;
using UnityEngine;
using UnityEngine.UI;

public class ShaPanClient : MonoBehaviour
{
    public static ShaPanClient ins;
    public FHTcpClient fhTcpClient;

    bool exit;

    private void OnEnable()
    {
        exit = false;
        ins = this;
        fhTcpClient = new FHTcpClient();
    }


    void Start()
    {
        Connect();
    }

    public void Connect()
    {
        string ip_port = File.ReadAllText(Path.Combine(Application.streamingAssetsPath, "ip_port.txt"));
        fhTcpClient.InitConfig(ip_port);
        fhTcpClient.DisConnected = () =>
        {

        };
        fhTcpClient.Connected = (client) =>
        {
        };

        Loom.RunAsync(() =>
        {
            while (!exit)
            {
                if (!fhTcpClient.IsOnline())
                {
                    fhTcpClient.StartConnect();
                }
            }
        });
    }

    private void OnDisable()
    {
        exit = true;
        if (fhTcpClient != null)
        {
            fhTcpClient.Close();
        }
    }


    public void OnDisConnect()   //断开连接
    {
        fhTcpClient.Close();
    }

    /// <summary>
    /// 转发对象
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="dataTypeEnum"></param>
    /// <param name="orderTypeEnum"></param>
    /// <param name="data"></param>
    public void Send<T>(DataTypeEnum dataTypeEnum, OrderTypeEnum orderTypeEnum, T data)
    {
        fhTcpClient.Send(dataTypeEnum, orderTypeEnum, data);
    }

    /// <summary>
    /// 转发16进制
    /// </summary>
    /// <param name="dataTypeEnum"></param>
    /// <param name="orderTypeEnum"></param>
    /// <param name="hexstr"></param>
    public void SendHex(DataTypeEnum dataTypeEnum, OrderTypeEnum orderTypeEnum, string hexstr)
    {
        fhTcpClient.SendHexStr(dataTypeEnum, orderTypeEnum, hexstr);
    }



}
